package com.webdrider.model.validators;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.common.model.abstracts.AbstractRequest;
import com.common.model.abstracts.AbstractValidator;
import com.common.security.abstracts.AbstractError;
import com.common.security.exceptions.ManagerException;
import com.webdrider.manager.action.snippet.DomainManager;
import com.webdrider.manager.action.snippet.TagManager;
import com.webdrider.manager.interfaces.IDomainManager;
import com.webdrider.manager.interfaces.ITagManager;
import com.webdrider.model.action.snippet.Domain;
import com.webdrider.model.action.snippet.Tag;
import com.webdrider.model.requests.snippet.SearchSnippetArticleRequest;
import com.webdrider.security.errors.SnippetError;
import com.webdrider.security.exceptions.SnippetException;

public class SearchSnippetArticleValidator extends AbstractValidator {

	@Override
	public boolean validate(AbstractRequest abstractRequest) {
		try {
			SearchSnippetArticleRequest request = null;
			
			if (abstractRequest instanceof SearchSnippetArticleRequest) {
				request = (SearchSnippetArticleRequest) abstractRequest;
			} else {
				error = new SnippetError(SnippetError.INVALID_REQUEST);
				return false;
			}
			
			Domain domain = request.getDomain();
			List<Tag> tags = request.getTags();
			
			IDomainManager domainManager = new DomainManager();
			ITagManager tagManager = new TagManager();
			
			if (domain == null || domain.getValue() == null) {
				error = new SnippetError(SnippetError.NO_DOMAIN_PROVIDED);
				return false;
			}
			
			int length = domain.getValue().length();
			if (length < AddSnippetDomainValidator.DOMAIN_MIN_LENGTH ||
					length > AddSnippetDomainValidator.DOMAIN_MAX_LENGTH) {
				error = new SnippetError(SnippetError.DOMAIN_BAD_FORMAT);
				return false;
			}
			
			if (!domainManager.exist(domain.getValue())) {
				error = new SnippetError(SnippetError.DOMAIN_NOT_FOUND);
				return false;
			} else {
				request.setDomain(domainManager.getDomain(domain.getValue()));
			}
			
			Set<Tag> tagSet = new HashSet<Tag>();
			for (Tag tag : tags) {
				if (tagManager.exist(tag.getValue())) {
					Tag resultTag = tagManager.getTag(tag.getValue());
					
					if (tagSet.contains(tag)) {
						error = new SnippetError(SnippetError.DUPLICATE_TAG);
						return false;
					} else {
						tagSet.add(resultTag);
					}
				}
			}
			request.setTags(new ArrayList<Tag>(tagSet));
			
			return true;
		} catch (ManagerException e) {
			error = new SnippetError(AbstractError.DATABASE_ERROR);
			return false;
		} catch (SnippetException e) {
			error = new SnippetError(AbstractError.DATABASE_ERROR);
			return false;
		}
	}

}
